package Test;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;
import okhttp3.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Decoder;
import weaver.general.Util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @author dusongsong
 * @date 2022年12月15日 09:18
 */
public class test04 {
    public static void main(String[] args) throws IOException {
        System.out.println(getUUIDStr());

    }
    public static String generateMD5(String input) {
        return DigestUtils.md5Hex(input);
    }
    public static String getTimestamp() {
        // 获取当前时间的毫秒时间戳
        long currentTimeMillis = System.currentTimeMillis();
        // 转换为秒时间戳
        long secondsSinceEpoch = currentTimeMillis / 1000;
        // 输出10位时间戳
        return String.format("%010d", secondsSinceEpoch);
    }
    public static String dateFormat(String date) {
        try {
            Date localDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
            SimpleDateFormat utcSDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            utcSDF.setTimeZone(TimeZone.getTimeZone("UTC"));
            return utcSDF.format(localDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }
    private static String handlerOrder(String orderType){
    Map<String, Function<String, Object>> functionMap = new HashMap<>();
    functionMap.put("PO", test04::test1);
    functionMap.put("INBOUND", test04::test2);
    functionMap.put("OUTBOUND", test04::test3);

    return (String) functionMap.get(orderType).apply("djaksdjlas");
    }


    private static String test1(String str){
        return str;
    }
    private static String test2(String str){
        return str;
    }
    private static String test3(String str){
        return str;
    }
    private static void fileUpload() {
        try {
            byte[] byteArray = {65, 66, 67, 68, 69}; // 这是一个包含"A", "B", "C", "D", "E"字符的字节数组

            // 将字节数组转换为InputStream
            InputStream inputStream = new ByteArrayInputStream(byteArray);
//            FileItemFactory factory = new DiskFileItemFactory();
//            ServletFileUpload upload = new ServletFileUpload(factory);
//            List<FileItem> multiparts = upload.parseRequest(request);
//            for (FileItem item : multiparts) {
//                baseBean.writeLog(">>>>>uploadfile.jsp>>>>>item=" + item);
//                if (!item.isFormField()) {
////                    String name = item.getName();
////                    baseBean.writeLog(">>>>>uploadfile.jsp>>>>>name=" + name);
////                    String fileSeparator = File.separator;
////                    baseBean.writeLog(">>>>>uploadfile.jsp>>>>>fileSeparator=" + fileSeparator);
////                    if (fileSeparator.equals("\\")) {
////                        path = path.replace("/", "\\");
////                    }
////                    baseBean.writeLog(">>>>>uploadfile.jsp>>>>>path=" + path);
////                    ensureDirectoryExists(realPath + path);
////                    String filePath = realPath + path + name;
////                    baseBean.writeLog(">>>>>uploadfile.jsp>>>>>filePath=" + filePath);
//                    // inputStream = item.getInputStream();
//                    // 写入文件
//                    writeInputStreamToFile(inputStream);
//
//                    baseBean.writeLog(">>>>>uploadfile.jsp>>>>>upload success");
//                }
//            }
            writeInputStreamToFile(inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static void writeInputStreamToFile(InputStream inputStream) throws IOException {

        try {
            String outputPath = "/Users/dusongsong/Downloads/test.jsp";
             FileOutputStream fileOutputStream = new FileOutputStream(outputPath);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                bufferedOutputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            System.err.println("An error occurred while processing the input stream: " + e.getMessage());
        }
    }

    public static boolean GetPDF(String data, String filePath) {
        BASE64Decoder base64 = new BASE64Decoder();
        try {
            byte[] bytes = base64.decodeBuffer(data);
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }


            try {
                Rectangle rectPageSize = new Rectangle(PageSize.A4);// A4纸张
                Document document = new Document(rectPageSize, 10, 10, 10, 10);// 上、下、左、右间距
                PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
                document.open();
                if (bytes != null) {
                    Image image = Image.getInstance(bytes);
                    PdfContentByte canvas = writer.getDirectContent();
                    writer.getPageNumber();
                    System.out.println("image-width=" + image.getWidth());
                    System.out.println("image-height=" + image.getHeight());
                    System.out.println("rectPageSize-height=" + rectPageSize.getWidth());
                    System.out.println("rectPageSize-width=" + rectPageSize.getHeight());
                    if (image.getHeight() >= rectPageSize.getHeight()) {
                        canvas.addImage(image, rectPageSize.getWidth() - 10, 0, 0, rectPageSize.getHeight() - 10, 0, 10);
                    } else {
                        canvas.addImage(image, 1000, 0, 0, image.getHeight(), -200, rectPageSize.getHeight() - image.getHeight() - 10);
                    }

                }

                document.close();
                writer.close();
            } catch (DocumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static boolean containsStringArray(String[] array, String target) {
        return Arrays.asList(array).contains(target);
    }


    public static String getUUIDStr() {
        String uuid = UUID.randomUUID().toString().toUpperCase();
        return uuid.replace("-", "");
    }

    public static long getDiffMinute(String begintime, String endtime) {
        Date data1 = DateUtil.parse(begintime);
        Date date2 = DateUtil.parse(endtime);
        return DateUtil.between(data1, date2, DateUnit.SECOND);
    }

    public static String stringToMD5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes());
        } catch (Exception e) {
            throw new RuntimeException("没有这个md5算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    public static String generateRandomNum() {
        int[] a = new int[6];
        Random r = new Random();
        a[0] = r.nextInt(6);
        for (int i = 1; i < 6; i++) {
            //数组存入6个数
            a[i] = r.nextInt(10);
            for (int j = 0; j < i; j++) {
                if (a[j] == a[i]) {
                    i--;
                    break;
                }
            }
        }
        // 遍历
        StringBuffer str = new StringBuffer();
        for (int s : a) {
            str.append(s);
        }
        return str.toString();
    }

    private static JSONObject sendOKHttpRequest(String apiUrl, String params) {
        JSONObject resultJson = new JSONObject();
        String code = "failure";
        String message = "";
        String data = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            if (!"".equals(result)) {
                data = result;
                code = "success";
            } else {
                message = "response result is null";
            }
        } catch (Exception e) {
            message = "response timeout";
            e.printStackTrace();
        }
        resultJson.put("code", code);
        resultJson.put("data", data);
        resultJson.put("message", message);
        return resultJson;
    }

    // 加密：传入参数密钥和原始内容的字节信息
    public static byte[] encrypt(byte[] secretKey, byte[] content, byte[] iv) {
        try {
            // 创建密码对象，需要传入算法名称/工作模式/填充方式
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            // 根据secretKey(密钥)的字节内容，"恢复"秘钥对象
            SecretKey keySpec = new SecretKeySpec(secretKey, "AES");
            // CBC模式需要生成一个16 bytes的initialization vector(IV参数 )
            IvParameterSpec ivps = new IvParameterSpec(iv); // 随机数封装成IvParameterSpec参数对象
            // 初始化秘钥:操作模式、秘钥、IV参数
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivps);
            // 根据原始内容(字节),进行加密
            byte[] data = cipher.doFinal(content);
            return join(iv, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 解密：传入参数密钥和机密后内容的字节信息
    public static byte[] decrypt(byte[] secretKey, byte[] input) {
        try {
            // 把input分割成IV和密文
            byte[] iv = new byte[16];
            byte[] data = new byte[input.length - 16];
            System.arraycopy(input, 0, iv, 0, 16);// IV参数
            System.arraycopy(input, 16, data, 0, data.length);// 密文
            System.out.println("IV参数：" + Arrays.toString(iv));// 输出IV参数
            // 创建密码对象，需要传入算法名称/工作模式/填充方式
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            // 根据secretKey(密钥)的字节内容，"恢复"秘钥对象
            SecretKey keySpec = new SecretKeySpec(secretKey, "AES");
            // 回复IV参数
            IvParameterSpec ivps = new IvParameterSpec(iv);
            // 初始化秘钥:操作模式、秘钥、IV参数
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivps);
            return cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 数组合并
    public static byte[] join(byte[] arr1, byte[] arr2) {
        byte[] arr = new byte[arr1.length + arr2.length];
        System.arraycopy(arr1, 0, arr, 0, arr1.length);
        System.arraycopy(arr2, 0, arr, arr1.length, arr2.length);
        return arr;
    }


    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; ++i) {
            sb.append(Integer.toHexString((bytes[i] & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    public static String stringToHex(String input) {
        StringBuilder hex = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            hex.append(String.format("%02X", (int) input.charAt(i)));
        }
        return hex.toString();
    }

    public static String stringToHex2(String input) {
        char[] chars = input.toCharArray();
        StringBuilder hex = new StringBuilder();
        for (char c : chars) {
            hex.append(Integer.toHexString((int) c));
        }
        return hex.toString();
    }

    public static String stringToHex3(String input) {
        byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
        StringBuilder hex = new StringBuilder();
        for (byte b : bytes) {
            hex.append(String.format("%02X", b));
        }
        return hex.toString();
    }

    public static String stringToHex4(String input) {
        byte[] bytes = input.getBytes();
        StringBuilder hex = new StringBuilder();
        for (byte b : bytes) {
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    public static String hexToString(String hex) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hex.length(); i += 2) {
            String hexSubstring = hex.substring(i, i + 2);
            int decimalValue = Integer.parseInt(hexSubstring, 16);
            sb.append((char) decimalValue);
        }
        return sb.toString();
    }

    public static String hexToString2(String hex) {
        byte[] bytes = new byte[hex.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            int index = i * 2;
            int decimalValue = Integer.parseInt(hex.substring(index, index + 2), 16);
            bytes[i] = (byte) decimalValue;
        }
        return new String(bytes, StandardCharsets.UTF_8);
    }

    public static String hexToString3(String hex) {
        byte[] bytes = hexToByteArray(hex);
        return new String(bytes, StandardCharsets.UTF_8);
    }

    private static byte[] hexToByteArray(String hex) {
        int length = hex.length();
        if (length % 2 != 0) {
            throw new IllegalArgumentException("Invalid hex string");
        }
        byte[] bytes = new byte[length / 2];
        for (int i = 0; i < length; i += 2) {
            bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return bytes;
    }

    /**
     * 发送 http post 请求，参数以原生字符串进行提交
     *
     * @param url
     * @param encode
     * @return
     */
    public static String httpPostRaw(String url, String stringJson, Map<String, String> headers, String encode) {
        if (encode == null) {
            encode = "utf-8";
        }
        String content = null;
        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;
        try {

            //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
            closeableHttpClient = HttpClients.createDefault();
            HttpPost httpost = new HttpPost(url);

            //设置header
            httpost.setHeader("Accept", "*/*");
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            //组织请求参数
            StringEntity stringEntity = new StringEntity(stringJson, encode);
            httpost.setEntity(stringEntity);


            //响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

    public static String sendOKHttp3Request(String paramJson) {
        String result = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, paramJson);
            String url = "http://58.241.13.10:11896/Api/PutData/ExecProcedureWithReturnJsonErrorToBody";
            Request request = new Request.Builder()
                    .url(url)
                    .method("POST", body)
                    .addHeader("Accept", "*/*")
                    .build();
            Response response = client.newCall(request).execute();
            result = response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }


}
